package com.gegong.imr.client.tasks;

import com.alibaba.fastjson.JSONObject;
import com.gegong.imessage.dto.TVmTask;
import com.gegong.imessage.dto.TaskResultDTO;
import com.gegong.imr.client.config.ImrCenterConfig;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.IOException;
import java.util.Map;

@Slf4j
public abstract class AbstractProcessCommandTask implements Runnable, OkHttpPage {

    private ImrCenterConfig centerConfig;

    protected int code = 1;
    protected String message;

    public AbstractProcessCommandTask(ImrCenterConfig centerConfig) {
        this.centerConfig = centerConfig;
    }

    protected void reportExecutedStatus(String taskId, int code, String message) throws TaskException {
        String operation = "上报任务执行结果";
        log.info(operation);
        TaskResultDTO taskResultDTO;
        try {
            taskResultDTO = TaskResultDTO.builder()
                    .taskId(taskId)
                    .code(code)
                    .message(message)
                    .build();
            RequestBody requestBody = RequestBody.create(defaultPostMediaType, JSONObject.toJSONString(taskResultDTO));
            Request request = new Request.Builder()
                    .url(centerConfig.urlForReportTaskState())
                    .headers(defaultHeaders)
                    .post(requestBody)
                    .build();
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful())
                throw TaskException.forFailure(operation, response);
            log.info("任务{}执行结果{}", taskId, taskResultDTO);
        } catch (IOException e) {
            throw TaskException.forException(operation, e);
        }
    }


    protected TVmTask queryTask(Map<String, Object> params) throws TaskException {
        String operation = "查询任务";
        RequestBody requestBody = RequestBody.create(defaultPostMediaType, JSONObject.toJSONString(params));
        Request request = new Request.Builder()
                .post(requestBody)
                .url(centerConfig.urlForGetClientCurrentTask())
                .build();

        try {
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) throw TaskException.forFailure(operation, response);
            assert response.body() != null;
            CenterResponse centerResponse = JSONObject.parseObject(response.body().string(), CenterResponse.class);
            if (!centerResponse.isSuccessful())
                throw TaskException.forBusiness(operation, centerResponse.getCode(), centerResponse.getMsg());
            return centerResponse.getData(TVmTask.class);
        } catch (IOException e) {
            throw TaskException.forException(operation, e);
        } catch (AssertionError e) {
            throw TaskException.forEmptyBody(operation, e);
        }

    }
}
